package com.darren.befriend.fragments;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.darren.befriend.HomeActivity;
import com.darren.befriend.R;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseUser;

public class UserInfoDetailFragment extends ProfileBaseFragment {

	private ParseObject mRequestedObject;

	/**
	 * 
	 * @param user
	 * @param visibleLike
	 *            : true:visible or false: invisible
	 * @return
	 */
	public static UserInfoDetailFragment makeInstance(ParseUser user,
			boolean isFriend, boolean isRequest, ParseObject requestedObject) {
		UserInfoDetailFragment fragment = new UserInfoDetailFragment();
		mUsr = user;
		mVisibleLike = true;
		mIsFriend = isFriend;
		isFriendRequest = isRequest;
		fragment.setRequestedObject(requestedObject);
		return fragment;
	}

	public ParseObject getRequestedObject() {
		return mRequestedObject;
	}

	public void setRequestedObject(ParseObject requestedObject) {
		this.mRequestedObject = requestedObject;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = super.onCreateView(inflater, container, savedInstanceState);
		mDislikeBtn.setVisibility(View.VISIBLE);
		mLikeBtn.setVisibility(View.VISIBLE);
		return v;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.like:

			if (isFriendRequest) {

				acceptRequest(mUsr);
			} else {

				acceptFriend(mUsr);
				mOnRelationshipChanged.relationshipChanged(mUsr);
			}

			mAfterAddFriend.setVisibility(View.VISIBLE);
			break;
		case R.id.dislike:

			if (isFriendRequest) {

				denyRequest(mUsr);
				FriendsFragment.mFriendList.remove(mUsr);
			} else {

				declineFriend(mUsr);
				mOnRelationshipChanged.relationshipChanged(mUsr);
			}

			if (getActivity() instanceof HomeActivity) {

				HomeActivity activity = (HomeActivity) getActivity();
				activity.removeFragmentFromStack();
			}

			break;
		case R.id.made_friend_chat:

			if (getActivity() instanceof HomeActivity) {

				HomeActivity activity = (HomeActivity) getActivity();
				activity.removeFragmentFromStack();
			}

			ChatFragment fragment = ChatFragment.makeInstance(mUsr);
			HomeActivity act = (HomeActivity) getActivity();
			act.switchContentWithNormalAnimation(fragment);

			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	private void declineFriend(ParseUser friend) {
		ArrayList<String> array = (ArrayList<String>) mCurrentUsr.get("Enemy");
		boolean isFound = false;
		for (String element : array) {
			String[] usr = element.split("\\$\\$\\$");
			if (friend.getUsername().equals(usr[0])) {
				isFound = true;
			}
		}

		if (!isFound) {
			String object = new String();
			int currentTime = (int) new Date().getTime() / 1000;
			object = String
					.format("%s$$$%d", friend.getUsername(), currentTime);
			array.add(object);
		}

		mCurrentUsr.put("Enemy", array);
		mCurrentUsr.saveInBackground();
	}

	@SuppressWarnings("unchecked")
	private void acceptFriend(ParseUser friend) {
		ArrayList<String> array = (ArrayList<String>) mCurrentUsr
				.get("Friends");
		boolean isFound = false;
		for (String frd : array) {

			if (frd.equals(friend.getUsername())) {

				isFound = true;
			}
		}

		if (!isFound) {

			array.add(friend.getUsername());
		}

		mCurrentUsr.put("Friends", array);
		ArrayList<String> array1 = (ArrayList<String>) friend.get("Friends");
		isFound = false;
		for (String frd : array1) {

			if (frd.equals(mCurrentUsr.getUsername())) {

				isFound = true;
			}
		}

		if (!isFound) {

			ParseObject request = ParseObject.create("Requests");
			request.put("Sender", mCurrentUsr.getUsername());
			request.put("Receiver", friend.getUsername());
			request.put("Resolve", false);
			request.saveInBackground();
			String fullName = mCurrentUsr.getUsername();
			if (fullName.contains("_local")) {

				fullName = fullName.replace("_local", "");
			}

			String msg = String.format("%s send you friend request.", fullName);
			ParsePush push = new ParsePush();
			push.setChannel(String.format("CH_%s", friend.getUsername()));
			JSONObject data = null;
			try {

				data = new JSONObject("{\"alert\": \" " + msg
						+ "\",\"badge\": \"Increment\"}");
			} catch (JSONException e) {

				e.printStackTrace();
			}

			push.setData(data);
			push.setExpirationTimeInterval(86400);
			push.sendInBackground();
		}

		mCurrentUsr.saveInBackground();
	}

	@SuppressWarnings("unchecked")
	private void acceptRequest(ParseUser requestedUser) {

		mRequestedObject.put("Resolve", true);
		mRequestedObject.saveInBackground();
		FriendsFragment.requestArray.remove(mRequestedObject);

		ArrayList<String> friends = (ArrayList<String>) mCurrentUsr
				.get("Friends");
		boolean isFound = false;
		for (String frd : friends) {

			if (frd.equals(requestedUser.getUsername())) {

				isFound = true;
			}
		}

		if (!isFound) {

			friends.add(requestedUser.getUsername());
		}

		mCurrentUsr.put("Friends", friends);

		// Send push
		String fullName = mCurrentUsr.getUsername();
		if (fullName.contains("_local")) {

			fullName = fullName.replace("_local", "");
		}

		String msg = String
				.format("%s accepted your friend request.", fullName);
		ParsePush push = new ParsePush();
		push.setChannel(String.format("CH_%s", requestedUser.getUsername()));
		JSONObject data = null;
		try {

			data = new JSONObject("{\"alert\": \" " + msg
					+ "\",\"badge\": \"Increment\"}");
		} catch (JSONException e) {

			e.printStackTrace();
		}

		push.setData(data);
		push.setExpirationTimeInterval(86400);
		push.sendInBackground();
	}

	@SuppressWarnings("unchecked")
	private void denyRequest(ParseUser requestedUser) {

		mRequestedObject.put("Resolve", true);
		mRequestedObject.saveInBackground();
		FriendsFragment.requestArray.remove(mRequestedObject);
		ArrayList<String> array = (ArrayList<String>) mCurrentUsr.get("Enemy");
		boolean isFound = false;
		for (String element : array) {
			String[] usr = element.split("\\$\\$\\$");
			if (requestedUser.getUsername().equals(usr[0])) {
				isFound = true;
			}
		}

		if (!isFound) {
			String object = new String();
			int currentTime = (int) new Date().getTime() / 1000;
			object = String.format("%s$$$%d", requestedUser.getUsername(),
					currentTime);
			array.add(object);
		}

		mCurrentUsr.put("Enemy", array);
		mCurrentUsr.saveInBackground();

		// Send push
		String fullName = mCurrentUsr.getUsername();
		if (fullName.contains("_local")) {

			fullName = fullName.replace("_local", "");
		}

		String msg = String
				.format("%s declined your friend request.", fullName);
		ParsePush push = new ParsePush();
		push.setChannel(String.format("CH_%s", requestedUser.getUsername()));
		JSONObject data = null;
		try {

			data = new JSONObject("{\"alert\": \" " + msg
					+ "\",\"badge\": \"Increment\"}");
		} catch (JSONException e) {

			e.printStackTrace();
		}

		push.setData(data);
		push.setExpirationTimeInterval(86400);
		push.sendInBackground();
	}
}
